<?php

class PurchasesController extends AppController {

    var $name = 'Purchases';
    var $uses = array('Purchase', 'Article', 'Supplier', 'Order'); //aca le decis cuales modelos vas a usar

    function beforeFilter() {
        parent::beforeFilter();

        //si no es un usuario con nivel = 2 o 1 no lo dejo acceder a las siguientes funciones de este controlador
        if (in_array($this->action, array('index', 'edit', 'delete', 'view')) and $this->Auth->user('id') and !(in_array($this->Auth->user('level'), array(1,2)))) {
            $this->redirect(array('user' => false, 'controller' => 'articles', 'action' => 'inicio'));
        }
        if (in_array($this->action, array('add')) and $this->Auth->user('id')) {
            $this->redirect(array('user' => false, 'controller' => 'articles', 'action' => 'inicio'));
        }
    }
    
    function index() {       
        $this->Purchase->recursive = 0;

        if (!empty($this->data)) {
            $datos = $this->data['Purchase'];
            $filtro = '';

            if (isset($datos['desde']) && trim($datos['desde']) != '') {
                if (isset($datos['hasta']) && trim($datos['hasta']) != '') {
            
                    list($d, $m, $a) = explode("/", $datos['desde']);
                    $fi = $a . '-' . $m . '-' . $d;

                    list($d, $m, $a) = explode("/", $datos['hasta']);
                    $ff = $a . '-' . $m . '-' . $d . ' 23:59:59';
            
                    $filtro .= " Purchase.purchase_date BETWEEN '" . $fi . "' AND '" . $ff ."'";
                }else{
                    list($d, $m, $a) = explode("/", $datos['desde']);
                    $fi = $a . '-' . $m . '-' . $d . ' 23:59:59';
            
                    $filtro .= " Purchase.purchase_date >= '" . $fi ."'";
                }
            }else{
                if (isset($datos['hasta']) && trim($datos['hasta']) != ''){
                    list($d, $m, $a) = explode("/", $datos['hasta']);
                    $ff = $a . '-' . $m . '-' . $d . ' 23:59:59';

                    $filtro .= " Purchase.purchase_date <= '" . $ff ."'";
                }else{
                    $filtro .= " 1";
                }
            }
            $this->paginate['order'] = array('Purchase.purchase_date' => 'ASC');
            $resultados = $this->paginate('Purchase', array($filtro));
//            pr($resultados);die;
            $this->set('purchases', $resultados);

            //guardo el filtro usado en session para despues recordarlo con el paginate
            $restricciones = array('filter' => $filtro, 'order' => $this->paginate['order']);
            $this->Session->write('search_conditions_purchases', $restricciones);
        } elseif ($this->Session->check('search_conditions_purchases')) {

            //si habia algun filtro guardado en session lo tengo que tomar y seguir aplicando el mismo
            //si estoy paginando
            if (isset($this->params['named']['limit']) || isset($this->params['named']['page'])) {
                $restricciones = $this->Session->read('search_conditions_purchases');

                //si esta acomodando por algun campo en particular
                if (isset($this->params['named']['sort'])) {
                    $this->paginate['order'] = array($this->params['named']['sort'] => $this->params['named']['sort']['direction']);
                } else {
                    //sino sigo aplicando el mismo que ya venia
                    $this->paginate['order'] = $restricciones['order'];
                }
                //si hay que seguir el filtro de empleados
                $resultados = $this->paginate('Purchase', array($restricciones['filter']));

                $this->set('purchases', $resultados);
            } else {
                //lo borro de la session
                $filtro = '';
                $this->Session->delete('search_conditions_purchases');
//                $this->paginate['order'] = array('Purchase.purchase_date' => 'DESC');
                $resultados = $this->paginate('Purchase', array($filtro));
                $this->set('purchases', $resultados);
            }
        } else {

            //le pongo un filtro por default
            $filtro = '';
            $this->paginate['order'] = array('Purchase.purchase_date' => 'DESC');
            $resultados = $this->paginate('Purchase', array($filtro));
            $this->set('purchases', $resultados);
        }
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Compra no válida', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('purchase', $this->Purchase->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $array_datos = $this->data;
            list($d, $m, $a) = explode("/", $array_datos['Purchase']['purchase_date']);
            $fecha_aux = $a . "-" . $m . "-" . $d;
            $array_datos['Purchase']['purchase_date'] = $fecha_aux;

            $this->Purchase->create();
            if ($this->Purchase->save($array_datos)) {
//				$this->Session->setFlash(__('La compra ha sido guardada', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La compra no se pudo guardar. Por favor, inténtelo de nuevo.', true));
            }
        }
        $articles = $this->Purchase->Article->find('list');
        $this->set(compact('articles'));
    }

    function edit($id = null){ 
        //empiezo una transaccion
        $this->Purchase->query('SET AUTOCOMMIT = 0;');
        $this->Purchase->query('START TRANSACTION;');
        $bandera = true; //la uso para ver si algo salio mal
        
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Compra no válida', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $array_datos = $this->data;
            list($d, $m, $a) = explode("/", $array_datos['Purchase']['purchase_date']);
            $fecha_aux = $a . "-" . $m . "-" . $d;
            $array_datos['Purchase']['purchase_date'] = $fecha_aux;
            $fecha_actual = date('Y-m-d');
            if($fecha_aux <= $fecha_actual){
                $compra_original = $this->Purchase->find('first', array('conditions' => array('Purchase.id' => $array_datos['Purchase']['id'])));
//                if(!(is_integer($array_datos['Purchase']['order_id']))){
//                    $array_datos['Purchase']['order_id'] == NULL;
//                }
                if ($this->Purchase->save($array_datos)) {
    //				$this->Session->setFlash(__('La compra ha sido guardada', true));
                        $id_nueva_compra = $this->Purchase->id; //despues de un save, asi obtenes el id del registro que guardarste
                    $compra_nueva = $this->Purchase->find('first', array('conditions' => array('Purchase.id' => $id_nueva_compra)));
                    $diferencia = $compra_original['Purchase']['purchase_amount'] - $compra_nueva['Purchase']['purchase_amount'];
                    $articulo = $this->Article->find('first', array('conditions' => array('Article.id' => $compra_original['Purchase']['article_id'])));
                    $articulo['Article']['amount_available'] = $articulo['Article']['amount_available'] - $diferencia;
                    if ($this->Article->save($articulo['Article'])) {
                        //Actualizo el pedido si no es compra inicial
                        if($array_datos['Purchase']['order_id'] == NULL){
                            $bandera = true;
                        }else{
                            $order = $this->Order->find('first', array('conditions' => array('Order.id' => $compra_nueva['Purchase']['order_id'])));
                            $order['Order']['date'] = $compra_nueva['Purchase']['purchase_date'];
                            $order['Order']['amount_recibed'] = $compra_nueva['Purchase']['purchase_amount'];
//                            pr($order);die;
                            if($this->Order->save($order['Order'])){
                                $bandera = true;
//                                echo "ENTRO";
                            }else{
                                $bandera = false;
                            }
                        }
                    }else{
                        $bandera=false;
                    }
                } else {
                    $bandera=false;
//                    $this->Session->setFlash(__('La compra no se pudo guardar. Por favor, inténtelo de nuevo.', true));
                }
            }else{
                $bandera=false;
            }
            
            if ($bandera) {
                $this->Purchase->query('COMMIT;');
                $this->Purchase->query('SET AUTOCOMMIT = 1;');
                $this->redirect(array('action' => 'index'));
            } else {//si hubo algun error hago un ROLLBACK deshaciendo todas estas consultas
                $this->Purchase->query('ROLLBACK;');
                $this->Purchase->query('SET AUTOCOMMIT = 1;');
                $this->Session->setFlash(__('La compra no se pudo guardar. Verifique que la Fecha de Compra sea menor que la fecha actual.', true));
            }
        }
          
        if (empty($this->data)) {
            $this->data = $this->Purchase->read(null, $id);
            //transformo la fecha para que se muestre con el formato dd/mm/yyyy
            $this->data['Purchase']['purchase_date'] = date('d/m/Y', strtotime($this->data['Purchase']['purchase_date']));
        }
        $articulos = $this->Article->find('all', array('fields' => array('Article.mark', 'Article.model', 'Article.id'), 'conditions' => array('Article.termination_date' => NULL)));
        $articles = array();
        foreach ($articulos as $art) {
            $articles[$art['Article']['id']] = $art['Article']['mark'] . ' - ' . $art['Article']['model'];
        }
        $pedidos = $this->Purchase->Order->find('all', array('fields' => array('Order.date', 'Order.id')));
        $orders = array();
        foreach ($pedidos as $ped) {
            $fecha = date('d/m/Y', strtotime($ped['Order']['date']));
            $orders[$ped['Order']['id']] = $fecha;
        }
        $suppliers = $this->Purchase->Supplier->find('list');
        $this->set(compact('articles', 'suppliers', 'orders'));
    }

    function delete($id = null) {
        //empiezo una transaccion
        $this->Purchase->query('SET AUTOCOMMIT = 0;');
        $this->Purchase->query('START TRANSACTION;');
        $bandera = true; //la uso para ver si algo salio mal

        //Aca actualizo el articulo perteneciente a la compra descontandole la cantidad comprada
        $purchase = $this->Purchase->query("SELECT purchases.article_id as articulo, purchases.order_id as pedido, purchases.purchase_amount as cantidad FROM purchases WHERE purchases.id = " . $id . ";");
        $article = $this->Article->find('first', array('conditions' => array('Article.id' => $purchase[0]['purchases']['articulo'])));
        $article['Article']['amount_available'] = $article['Article']['amount_available'] - $purchase[0]['purchases']['cantidad'];
        
        if($this->Article->save($article['Article'])){//Fin actualizacion articulo
                if ($this->Purchase->delete($id)) {
                    if($this->Order->delete($purchase[0]['purchases']['pedido'])){//Elimino el pedido asociado a la compra
                    $bandera = true;
                }else{
                    $bandera = false;
                }
            }else{
                $bandera = false;
            }
        }else{
            $bandera = false;
        }
        
        if ($bandera) {
            $this->Purchase->query('COMMIT;');
            $this->Purchase->query('SET AUTOCOMMIT = 1;');
            $this->redirect(array('action' => 'index'));
        } else {//si hubo algun error hago un ROLLBACK deshaciendo todas estas consultas
            $this->Purchase->query('ROLLBACK;');
            $this->Purchase->query('SET AUTOCOMMIT = 1;');
            $this->Session->setFlash(__('Compra no eliminada', true));
        }

        $this->redirect(array('action' => 'index'));
    }

    function get_article($id){
        
        $article = $this->Article->find('first', array('conditions' => array('Article.id' => $id)));
        return $article['Article']['mark']. ' - '.$article['Article']['model'];
    }
}